<template>
  <div>
    <div id="myChart" class="myChart"></div>
  </div>
</template>

<script setup>// 引入必要的库
import * as echarts from 'echarts';
import { onMounted, ref, watch } from 'vue';
// 存储图表实例
let myChart;
// 数据存储
const dataPoints = ref([]);
// const { isPlay } = defineProps(['isPlay'])
const props = defineProps({ isPlay: Boolean });
console.log(props.isPlay, 'echarts');
const emit = defineEmits(['changePlay'])

onMounted(() => {
  // 初始化图表
  initChart();
  // 模拟数据实时更新
  // setInterval(() => {
  //   const newData = Math.random();
  //   dataPoints.value.push(newData);
  //   updateChart();
  // }, 1000);
});

// 初始化图表
const initChart = () => {
  // 获取图表容器元素
  const chartDom = document.getElementById('myChart');
  // 初始化图表实例
  myChart = echarts.init(chartDom);

  // 配置图表选项
  const option = {
    xAxis: {
      type: 'category',
      data: dataPoints.value.slice(-30).map((_, index) => new Date(new Date().getTime() + index * 1000).toLocaleString())
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        data: dataPoints.value.slice(-30),
        type: 'line',
        smooth: true,
        itemStyle: {
          color: '#c23531'
        },
        lineStyle: {
          width: 2
        },
        animation: false // 初始化时不触发动画
      }
    ],
    tooltip: {
      trigger: 'axis',
      formatter: (params) => {
        let str = '';
        params.forEach((item) => {
          str += `坐标: (${item.name}, ${item.value})<br>`;
        });
        return str;
      }
    }
  };

  // 使用配置项设置图表
  myChart.setOption(option);
};

// 更新图表数据
const updateChart = () => {
  myChart.setOption({
    xAxis: {
      data: dataPoints.value.slice(-30).map((_, index) => new Date(new Date().getTime() + index * 1000).toLocaleString())
    },
    series: [
      {
        data: dataPoints.value.slice(-30),
        animation: true // 仅在数据更新时触发动画
        // 配置图表颜色
      }
    ]
  });
};
let timer = null;
watch(() => props.isPlay, (newValue, oldValue) => {
  console.log(`新值:${newValue} ——— 老值:${oldValue}`);
  if (newValue) {
    // 播放
    timer = setInterval(() => {
      const newData = Math.random();
      dataPoints.value.push(newData);
      updateChart();
    }, 1000);
  } else {
    // 暂停
    clearInterval(timer)
  }
});


</script>

<style scoped>
.myChart {
  width: 100%;
  height: 400px;
}
</style>